const { Article, Sequelize, Tag } = require('../models')
const { Op } = Sequelize
module.exports = [
  {
    /**
     * @api {post} /api/article/list [文章列表]
     * @apiGroup Article
     * @apiPermission none
     * @apiParam  {String} [title] 标题,模糊搜索
     * @apiParam  {Number} [categoryId] 按分类
     * @apiParam  {Number} [offset=0]
     * @apiParam  {Number} [limit=10]
     *
     */
    url: '/api/article/list',
    method: 'post',
    request: async (req, res) => {
      const { offset, limit, title = null, categoryId = null } = req.body
      let wheres = {}
      if (title) wheres.title = { [Op.like]: `%${title}%` }
      if (categoryId) wheres.categoryId = categoryId
      try {
        const result = await Article.findAndCountAll({
          where: wheres,
          distinct: true,
          include: [
            {
              association: Article.Category,
              attributes: ['id', 'name']
            }, {
              association: Article.ArticleTags,
              as: 'tags'
            }
            // {
            //   association: Article.Comments,
            //   attributes: {
            //     // include: [[fn('COUNT', col('comments.articleId')), '<=', col('article.id'), 'comment_count']]
            //   }
            // }
          ],
          offset: Number(offset) || 0,
          limit: Number(limit) || 10
        })
        res.json(result)
      } catch (error) {
        throw error
      }
    }
  }, {
    /**
     * @api {get} /api/article/:id [文章详情]
     * @apiGroup Article
     * @apiPermission none
     * @apiDescription article详情
     * @apiParam  {Number} id 文章id
     */
    url: '/api/article/:id',
    method: 'get',
    request: async (req, res) => {
      try {
        const article = await Article.findOne({
          where: {
            id: req.params.id
          },
          attributes: { exclude: [ 'categoryId' ] },
          include: [
            {
              association: Article.Category,
              attributes: ['id', 'name']
            },
            {
              association: Article.ArticleTags,
              attributes: ['id', 'name']
            }
          ]
        })
        if (article) {
          res.json(article)
        } else {
          res.json({ msg: '找不到您想要的' })
        }
      } catch (error) {
        throw error
      }
    }
  },
  {
    /**
     * @api {post} /api/article/add [新增文章]
     * @apiGroup Article
     * @apiPermission none
     * @apiParam  {String} title 文章名称
     * @apiParam  {String} [desc] 描述
     * @apiParam  {String} content 内容
     * @apiParam  {Array} [tagsId] 文章标签
     * @apiParam  {Number} [categoryId] 分类
     *
     */
    url: '/api/article/add',
    method: 'post',
    request: async (req, res) => {
      try {
        const { tagsId } = req.body
        let tags = []
        if (typeof (tagsId) === 'string') {
          tagsId.split(',').forEach(item => {
            tags.push(Number(item))
          })
        } else {
          tags = tagsId
        }

        let article = await Article.create(req.body, {
          include: [
            {
              association: Article.ArticleTags
            }
          ]
        })
        let tagList = await Tag.findAll({
          where: { id: tags },
          attributes: ['id', 'name']
        })
        await article.setTags(tagList)
        res.json({ msg: '创建成功',
          article: req.body
        })
      } catch (error) {
        res.json({ msg: '创建失败', error })
      }
    }
  },
  {
    /**
     * @api {delete} /api/article/delete/:id [删除文章]
     * @apiGroup Article
     * @apiPermission none
     * @apiParam  {Number} id 文章id
     */
    url: '/api/article/delete/:id',
    method: 'delete',
    request: async (req, res) => {
      try {
        const { id } = req.params
        const article = await Article.findOne({
          where: { id }
        })
        if (!article) return res.json({ msg: '找不到您想要的' })
        await Article.destroy({ where: { id } })
        res.json({ msg: '删除成功', id })
      } catch (error) {
        res.json({ msg: '删除失败', error })
      }
    }
  },
  {
    /**
     * @api {put} /api/article/update [更新文章]
     * @apiGroup Article
     * @apiPermission none
     * @apiParam  {Number} id 文章id
     * @apiParam  {String} title 文章名称
     * @apiParam  {String} [desc] 描述
     * @apiParam  {String} content 内容
     * @apiParam  {Array} [tagsId] 文章标签
     * @apiParam  {Number} [categoryId] 分类
     */
    url: '/api/article/update',
    method: 'put',
    request: async (req, res) => {
      try {
        const { id, tagsId } = req.body
        let tags = []
        if (typeof (tagsId) === 'string') {
          tagsId.split(',').forEach(item => {
            tags.push(Number(item))
          })
        } else {
          tags = tagsId
        }
        const article = await Article.findOne({ where: { id } })
        if (!article) return res.json({ msg: '没有该记录' })
        await Article.update(req.body, {
          where: { id }
        })
        let tagList = await Tag.findAll({
          where: { id: tags },
          attributes: ['id', 'name']
        })
        await article.setTags(tagList)
        res.json({ msg: '更新成功', id })
      } catch (error) {
        res.json({ msg: '更新失败', error })
      }
    }
  }
]
